import { Form, Input, Modal } from "antd";
import type { InputRef } from "antd";
import { useMainStore } from "@/store/mainStore";
import { useShallow } from "zustand/react/shallow";
import { useState, useRef, useEffect } from "react";

type HotkeyModalProps = {
  onOk: (hotkey: string) => void;
};

const HotkeyModal = (props: HotkeyModalProps) => {
  const { hotkeyModalVisible, hotkeyModalInfo } = useMainStore(
    useShallow((state) => ({
      hotkeyModalVisible: state.hotkeyModalVisible,
      hotkeyModalInfo: state.hotkeyModalInfo,
    }))
  );
  const [hotkey, setHotkey] = useState("");
  const inputRef = useRef<InputRef>(null);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const keys = [];
    if (e.ctrlKey) keys.push("Ctrl");
    if (e.shiftKey) keys.push("Shift");
    if (e.altKey) keys.push("Alt");
    if (e.metaKey) keys.push("Win");

    let key = e.key.toUpperCase();
    if (key == " ") key = "SPACE";
    if (key == "ARROWLEFT") key = "Left";
    if (key == "ARROWRIGHT") key = "Right";
    if (key == "ARROWUP") key = "Up";
    if (key == "ARROWDOWN") key = "Down";
    if (!["CONTROL", "SHIFT", "ALT", "META"].includes(key)) {
      keys.push(key);
    }
    setHotkey(keys.join(" + "));
  };

  const cancel = () => {
    useMainStore.setState({
      hotkeyModalVisible: false,
      hotkeyModalInfo: { id: 0, hotkey: "" },
    });
    setHotkey("");
  };

  useEffect(() => {
    if (hotkeyModalVisible) {
      setTimeout(() => inputRef.current?.focus());
    }
  }, [hotkeyModalVisible]);

  useEffect(() => {
    if (hotkeyModalVisible) {
      setHotkey(hotkeyModalInfo.hotkey);
    }
  }, [hotkeyModalVisible, hotkeyModalInfo]);

  return (
    <Modal
      title="全局快捷键"
      width={400}
      open={hotkeyModalVisible}
      keyboard={false}
      onCancel={cancel}
      onOk={() => {
        props.onOk(hotkey);
        cancel();
      }}
      destroyOnClose
      maskClosable={false}
      okText="确定"
      cancelText="取消"
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 5,
        }}
      >
        <span style={{ whiteSpace: "nowrap" }}>快捷键:</span>
        <Input
          allowClear
          ref={inputRef}
          placeholder="请输入快捷键"
          value={hotkey}
          onKeyDown={handleKeyDown}
          onClear={() => {
            setHotkey("");
          }}
        />
      </div>
    </Modal>
  );
};

export default HotkeyModal;
